<?php
//一个登陆页面
//登陆以后跳转到主页-》主页改版，加入个人中心于标签页中
//更新传入题目id后，word_model里面的getCount的计算方法
class Login extends CI_Controller
{
	protected static $apikey = "a7f7ad617f2f54a6acd5d51828abcfdc";
	public function __construct()
	{
		 
		parent::__construct();
		$this->load->model('user_model');
		$this->load->library('session');
		$this->load->helper('url');
	}
	public function index()//已被禁用
	{
		$data = array();
		if(isset($_SESSION['user']))
		{
			$data['user'] = $_SESSION['user'];
			$data['flag'] = 1;
		}
		else
		{
			$data['flag'] = 0;
		}
		$this->load->view('login/login',$data);
	}
	public function login()
	{
		$user = $this->input->post('user');
		$pass = $this->input->post('pass');
		if(empty($pass)||empty($user))
		{
			echo json_encode(array('code' => 'un'));
	     	exit;
		}
		$input = array('user'=>$user,'pass'=>$pass);
		if($this->checkInput($input) || !$this->checkNumFormat($input['user']))
		{
			echo json_encode(array('code' => 'error'));
	     	exit;
		}
		if($this->user_model->getRight($input))
		{
			$_SESSION['user'] = $user;
			$_SESSION['id'] = $this->user_model->getID($input);
			
			echo json_encode(array('code' => 'success'));
			
		}
		else
		{
			$this->user_model->addUser($user);
			echo json_encode(array('code' => 'signup'));
		}
	}

	public function varifyPhone()
	{
		if(!$this->checkNumFormat($this->input->post('phone')))
		{
			echo json_encode(array('code' => 'error'));
	     	exit;
		}
		$code= $this->randNum();
		$mobile = $this->input->post('phone');
		$text="【GET牛】您的验证码是".$code;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);


        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $data=array('text'=>$text,'apikey'=>Login::$apikey,'mobile'=>$mobile);
        $json_data = $this->send($ch,$data);
        $array = json_decode($json_data,true);
        if($array['code'] == 0)
        {
        	$_SESSION['password'] = $code;
            //var_dump($array);
        }
        else
        {
        	//echo json_encode(array(''))
        }
           echo $json_data;
        curl_close($ch);
	}

    protected function send($ch,$data)
    {
        curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        return curl_exec($ch);
    }
    protected function randNum()
    {
    	//生成四位数的随机数字
    	$num = '';
    	for($i=0;$i<4;$i++)
    	{
    		$num.=rand(0,9);
    	}
    	return $num;
    }
	protected function checkNumFormat($phone)
	{
		if(preg_match('/^1[3|4|5|8|9][0-9]\d{4,8}$/',$phone) == true)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}


   
?>